<?php

namespace App\Admin\Actions;

use App\Models\JobpositionModel;
use App\Models\JobPositionUpdateModel;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class JobPositionUpdateActions extends RowAction
{
    /**
     * @return string
     */

    public function __construct($type='')
    {
        $title = [
            2=>'确认',
            3=>'驳回',
        ][$type]??'';
        $this->type = $type;
        parent::__construct($title);
    }

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $id = $this->getKey();
        $type = $request->get('type');
        if ($type == 2) {
            $info = JobPositionUpdateModel::query()->where('id', $id)->first();
            $updateArray = [];
            foreach ($info['content'] as $item) {
                $updateArray[$item['key']] = $item['new'];
            }
            JobpositionModel::query()->where('id',$info['job_position_id'])->update($updateArray);
        }
        JobPositionUpdateModel::query()->where('id', $id)->update([
            'cur_status' => $type,
        ]);
        return $this->response()
            ->success('处理完成')
            ->refresh();
    }

    /**
     * @return array
     */
    public function confirm()
    {
        return ['Confirm?', '确认审核此条修改吗？'];
    }
    public function html()
    {
        // 获取当前行数据ID
        // 这里需要添加一个class, 和上面script方法对应
        $this->appendHtmlAttribute('style','margin-right:10px');
        if ($this->type == 2){
            $this->appendHtmlAttribute('class','btn btn-success btn-sm');
        }else{
            $this->appendHtmlAttribute('class','btn btn-primary btn-sm');
        }
        return parent::html();
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            'type' => $this->type,
        ];
    }
}
